package com.sz.ruichar.service.beans;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sz.ruichar.entity.beans.TUserCheckInLog;
import com.sz.ruichar.entity.beans.TUserScore;
import com.sz.ruichar.entity.beans.TUserScoreLog;
import com.sz.ruichar.entity.enums.ScoreAddTypeEnum;
import com.sz.ruichar.entity.enums.ScoreLogTypeEnum;
import com.sz.ruichar.entity.model.constant.Constant;
import com.sz.ruichar.entity.model.constant.MsgException;
import com.sz.ruichar.interfs.beans.ITUserCheckInLogService;
import com.sz.ruichar.service.mapper.beans.TUserCheckInLogMapper;
import com.sz.ruichar.service.mapper.beans.TUserScoreMapper;

/**
 * <p>
 * 用户签到流水日志 服务实现类
 * </p>
 *
 * @author 5beans
 * @since 2017-12-26
 */
@Service
public class TUserCheckInLogServiceImpl extends ServiceImpl<TUserCheckInLogMapper, TUserCheckInLog> implements ITUserCheckInLogService {

	@Resource
	TUserCheckInLogMapper checkInLogMapper;
	@Resource
	TUserScoreMapper userScoreMapper;
	@Value("${addScore}")
	int addScore;
	
	@Override
	@Transactional
	public Map<String,Object> checkIn(String openid)  {
		Map<String,Object> resultMap = new HashMap<>();
		//增加签到日志
		TUserCheckInLog checkInLog = new TUserCheckInLog();
		checkInLog.setOpenid(openid);
		checkInLog.insert();
		//更新积分
		TUserScore score = new TUserScore();
		score.setOpenid(openid);
		score = userScoreMapper.selectOne(score);
		if(null == score){
//			score = new TUserScore();
//			score.setOpenid(openid);
//			score.setScore(Constant.initScore);
//			score.insert();
		}else{
			//更新积分
			score.setScore(score.getScore()+addScore);
			score.updateById();
			//更新积分日志
			TUserScoreLog scoreLog = new TUserScoreLog();
			scoreLog.setOpenid(openid);
			scoreLog.setScore(addScore);
			scoreLog.setType(ScoreLogTypeEnum.checkin.getCode());
			scoreLog.setAddType(ScoreAddTypeEnum.add.getCode());
			scoreLog.insert();
		}
		resultMap.put("addScore", addScore);
		resultMap.put("tsp", new Date());
		return resultMap;
		
	}

	@Override
	public Map<String,Object> getTodayCheckInTime(String openid) {
		Integer checkInTime = checkInLogMapper.getTodayCheckInTime(openid);
		boolean isCheckIn = false;
    	if(checkInTime>0){
    		isCheckIn = true;
    	}
    	Map<String,Object> result = new HashMap<>();
    	result.put("isCheckIn", isCheckIn);
    	result.put("checkTime", checkInTime);
    	result.put("tsp", new Date());
    	result.put("addScore", addScore);
		return result;
	}
	
}
